package net.kevin.demo.hessian.controller;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.remoting.caucho.HessianExporter;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/rpcServer")
public class RemoteServerAction implements ApplicationContextAware {
	private ApplicationContext act;

	private Logger logger = LoggerFactory.getLogger(RemoteServerAction.class);

	@RequestMapping(value = "/{module}", method = RequestMethod.POST)
	public void handler2(@PathVariable String module,
			@RequestParam(value = "interface", required = true) String interfaceName, HttpServletRequest req,
			HttpServletResponse resp) {
		try {
			Class<?> clazz = ClassUtils.forName(interfaceName, act.getClassLoader());
			Object bean = act.getBean(clazz);
			HessianExporter hessianExporter = new HessianExporter();
			hessianExporter.setServiceInterface(clazz);
			hessianExporter.setService(bean);
			hessianExporter.prepare();
			OutputStream os = resp.getOutputStream();
			hessianExporter.invoke(req.getInputStream(), os);
		} catch (Throwable e) {
			logger.error("Invoke RPC Failue", e);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		act = applicationContext;
	}
}
